import { getIP, getStaticWorks, getWorks } from '@/apis'
import { Helmet, Link, useLocation, useModel, useNavigate } from '@umijs/max'
import { useEffect, useState } from 'react'
import { Outlet } from 'react-router'
import menu from '../../config/routes'
import styles from './index.less'

const Layouts = () => {
  const { works, setWorks, setPhotography } = useModel('global')
  const [worksIndex, setWorksIndex] = useState<number>(-1)
  const [labIndex, setLabIndex] = useState<number>(-1)
  const navigate = useNavigate()
  const [currentPath, setCurrentPath] = useState<(typeof menu)[number]>(menu[0])
  // 监听路由变化的hooks
  const location = useLocation()
  useEffect(() => {
    const searchParams = Number(new URLSearchParams(location.search).get('type') || -1)
    setWorksIndex(searchParams)

    // 如果是lab页面，设置labIndex，也使用type参数，默认为0（WaterMark）
    if (location.pathname === '/lab') {
      const labType = Number(new URLSearchParams(location.search).get('type') || 0)
      setLabIndex(labType)
    }

    setCurrentPath(menu.find((item) => item.path === location.pathname) || menu[0])
  }, [location])

  const getData = async () => {
    setWorks([])
    const { error: err1, result: res1 } = await getWorks()
    const { error: err2, result: res2 } = await getStaticWorks()
    if (!err1) {
      setWorks(() => res1)
    }
    if (!err2) {
      setWorks((prev: any[]) =>
        [...prev, ...res2.reverse()].filter((_) => {
          const isPhotography = _.category === 'Photo'
          if (isPhotography) {
            setPhotography(_.data)
            return false
          } else {
            return true
          }
        })
      )
    }
    const { error: err3, result: res3 } = await getIP()
    console.log(err3, res3)
  }

  useEffect(() => {
    getData()
  }, [])

  const handleClick = (e: any) => {
    // 阻止冒泡
    e.stopPropagation()
    const target = e.target as Element
    const liElement = target.closest('li')
    const idx = Number(liElement?.dataset.category)
    if (idx < works.length && idx >= -1) {
      navigate({
        pathname: '/works',
        search: `?type=${idx}`
      })
    }
  }

  // Lab菜单点击处理
  const handleLabClick = (e: any) => {
    // 阻止冒泡
    e.stopPropagation()
    const target = e.target as Element
    const liElement = target.closest('li')
    const idx = Number(liElement?.dataset.category)
    if (idx >= -1 && idx <= 1) {
      // 目前只有两个子项：WaterMark(0)和Panorama(1)
      navigate({
        pathname: '/lab',
        search: `?type=${idx}`
      })
    }
  }

  return (
    <div className={styles.layouts}>
      <Helmet>
        <script type="application/ld+json">
          {`
            {
              "@context": "https://schema.org",
              "@type": "WebSite",
              "name": "Zusheng Studio",
              "url": "https://zusheng.cc/",
              "description": "Zusheng Studio是一个展示创意设计、摄影作品与文章的个人网站。",
              "potentialAction": {
                "@type": "SearchAction",
                "target": "https://zusheng.cc/search?q={search_term_string}",
                "query-input": "required name=search_term_string"
              }
            }
          `}
        </script>
        <script type="application/ld+json">
          {`
            {
              "@context": "https://schema.org",
              "@type": "Organization",
              "name": "Zusheng Studio",
              "url": "https://zusheng.cc",
              "logo": "https://zusheng.cc/favicon.png",
              "sameAs": [
                "https://blog.zusheng.cc"
              ]
            }
          `}
        </script>
      </Helmet>
      <header className={styles.header}>
        <div
          className={styles.title}
          onClick={() =>
            navigate({
              pathname: '/'
            })
          }
        >
          Zusheng Studio
        </div>
        <ul className={styles.list}>
          {menu.map((item) => (
            <li key={item.path} className={currentPath.path === item.path ? styles.active : ''}>
              <Link to={item.path}>{item.name}</Link>
              {item.name === 'Works' && location.pathname === '/works' && (
                <ul className={styles.subList} onClick={handleClick}>
                  <li data-category={-1} className={worksIndex === -1 ? styles.active : ''}>
                    All
                  </li>
                  {works?.map((work, key) => (
                    <li
                      data-category={key}
                      className={worksIndex === key ? styles.active : ''}
                      key={'works-sub-' + key}
                    >
                      {work.category}
                    </li>
                  ))}
                </ul>
              )}
              {item.name === 'Lab' && location.pathname === '/lab' && (
                <ul className={styles.subList} onClick={handleLabClick}>
                  <li data-category={0} className={labIndex === 0 ? styles.active : ''}>
                    WaterMark
                  </li>
                  <li data-category={1} className={labIndex === 1 ? styles.active : ''}>
                    Panorama
                  </li>
                </ul>
              )}
            </li>
          ))}
        </ul>
        <div className={styles.copy}>
          <p>© 2025 Zusheng Studio. All rights reserved.</p>
          <p>粤ICP备2024268087号-1</p>
        </div>
      </header>
      {/* 移动版菜单 */}
      <header className={styles.mobileHeader}>
        <div className={styles.content}>
          <div
            className={styles.title}
            onClick={() =>
              navigate({
                pathname: '/'
              })
            }
          >
            Zusheng Studio
          </div>

          <ul className={styles.list}>
            {menu
              .filter((_) => _?.component)
              .map((item) => (
                <li key={item.path} className={currentPath.path === item.path ? styles.active : ''}>
                  <Link to={item.path} replace>
                    {item.name}
                  </Link>
                </li>
              ))}
          </ul>
        </div>
      </header>
      <main className={styles.content}>
        <Outlet />
      </main>
    </div>
  )
}

export default Layouts
